package com.sentiment.servlet;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.bson.types.ObjectId;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sentiment.bean.OperationInfo;
import com.sentiment.database.bean.CrawlInfo;
import com.sentiment.database.bean.DailyReport;
import com.sentiment.report.DailyReportUtils;
import com.sentiment.tools.Format;

/**
 * Servlet implementation class DailySentimentServlet
 */
@WebServlet("/DailySentimentServlet")
public class DailySentimentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	// 分页时每页显示的数量
	private int pageview = 10;
	private DailyReportUtils reportUtils = new DailyReportUtils();
	private static final Logger LOG = LoggerFactory.getLogger(DailySentimentServlet.class);

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub

		String methodName = request.getParameter("method");	
		try {
			Method method = getClass().getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
			method.invoke(this, request, response);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

	/**
	 * 生成今日报告（后端方法）
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void creatDailySentiment(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		reportUtils.createTodayReport();
		getTodayReport(request, response);
	}

	/**
	 * 得到今日报告列表（后端方法）
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void getTodayReport(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// List<DailyReportMini> reportminis = new ArrayList<>();
		List<DailyReport> reports = null;
		reports = reportUtils.findDailyReport(new Date());

		// for (int i = 0; i < reports.size(); i++) {
		// DailyReport report = reports.get(i);
		// DailyReportMini reportmini = new DailyReportMini();
		// reportmini.setId(report.get_id());
		// reportmini.setTitle(report.getTitle());
		// reportmini.setStatus(report.getStatus());
		// String text = report.getText().get(0);
		// if (text.length() <= 100)
		// reportmini.setText(text);
		// else
		// reportmini.setText(text.substring(0, 100));
		// reportminis.add(reportmini);
		// }

		StringBuilder sbd = new StringBuilder();
		if (reports != null && !reports.isEmpty()) {
			sbd.append("{\"reports\":");
			sbd.append("[");
			for (DailyReport report : reports) {
				sbd.append(report.toJson() + ",");
			}
			sbd.deleteCharAt(sbd.length() - 1);
			sbd.append("]");
			sbd.append("}");
		}

		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(sbd.toString());

	}

	/**
	 * 修改一篇DailyReport的状态信息，传入参数为id（后端方法）
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	public void changeReportStatus(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String id = request.getParameter("id");
		boolean status = reportUtils.updateStatus(new ObjectId(id));

		response.setCharacterEncoding("utf-8");
		response.getWriter().print(status);
	}

	/**
	 * 得到每日的报告列表（前端方法）
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void getReportsByPage(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 第一页为pagenum值为1
		int pagenum = Integer.parseInt(request.getParameter("pagenum"));

		Calendar calendar = Calendar.getInstance();
		long next = System.currentTimeMillis() - (pagenum - 1) * 10 * 24 * 60 * 60 * 1000;
		calendar.setTimeInMillis(next);
		// calendar定位到该页的开始日期

		List<String> resultDate = new ArrayList<String>();
		for (int i = 0; i < pageview; i++) {
			String str = Format.date2String(calendar.getTime(), 3);
			String[] split = str.split("_");
			String data = split[0] + "年" + split[1] + "月" + split[2] + "日舆情报告";
			resultDate.add(data);
			next -= 24 * 60 * 60 * 1000;
			calendar.setTimeInMillis(next);
		}
		List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
		for (int i = 0; i < pageview; i++) {
			JSONObject object = new JSONObject();
			object.put("title", resultDate.get(i));
			jsonObjects.add(object);
		}
		StringBuilder sb = new StringBuilder();
		if (jsonObjects != null) {
			sb.append("{");
			sb.append("\"recordsTotal\":" + pageview + ",");
			sb.append("\"titles\":" + jsonObjects);
			sb.append("}");
		}

		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(sb.toString());

	}
	
	/**
	 * 根据报告时间得到报告详细信息（前端方法）
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void getReportByDate(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 接收 Ajax 请求传输的 id
		String title = request.getParameter("title");
		List<DailyReport> reportlist = null;
		reportlist = reportUtils.findDailyReport(Format.string2Date(title, 3), true);
		StringBuilder sbd = new StringBuilder();
		if (reportlist != null && !reportlist.isEmpty()) {
			sbd.append("{\"reports\":");
			sbd.append("[");
			for (DailyReport report : reportlist) {
				sbd.append(report.toJson() + ",");
			}
			sbd.deleteCharAt(sbd.length() - 1);
			sbd.append("]");
			sbd.append(",\"title\":\"title\"}");
		} else {
			sbd.append("{\"info\":\"" + OperationInfo.TodayNoReport + "\"}");
		}
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(sbd.toString());
	}

	/**
	 * 根据报告 id 得到报告详细信息（后端方法）
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void getReportById(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		// 接收 Ajax 请求传输的 id
		String id = request.getParameter("id");
		DailyReport report = reportUtils.findDailyReport(new ObjectId(id));
		StringBuilder sbd = new StringBuilder();
		if (report != null) {
			sbd.append("{\"report\":" + report.toJson() + "}");
		} else {
			sbd.append("{\"report\":\"" + OperationInfo.ReportNotFound + "\"}");
		}

		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(sbd.toString());
	}

	/**
	 * 删除微博意见（后端方法）
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void deleteOpinions(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String id = request.getParameter("id");
		String checkarray = request.getParameter("checkarray");

		DailyReport report = reportUtils.findDailyReport(new ObjectId(id));
		if (checkarray != null && checkarray != "") {
			String[] checkid = checkarray.split("_");

			List<String> opinionid = report.getWeiboOpinion_id();
			for (int i = 0; i < checkid.length; i++) {
				// 删除 DailyReport 表中微博 id
				opinionid.remove(checkid[i]);
				// 删除 CrawInfo 表中微博信息
				CrawlInfo info = new CrawlInfo();
				info.set_id(checkid[i]);
				// dbu.remove(info.toDocument_id(), new String[] {"_id"});
			}
		}
		// dbu.closeConnection();
		// report.setStatus(true);
		// boolean publish = false;
		// publish = db.update(report.toDocument_id(), new String[] { "_id" },
		// report.toDocument_id(),
		// new String[] { "weiboOpinion_id", "status" });

		// db.closeConnection();

		// response.setCharacterEncoding("UTF-8");
		// response.getWriter().print(publish);

	}

	/**
	 * 每日舆情历史信息（后端方法）
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void sentmentHistory(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		int page = Integer.parseInt(request.getParameter("pagenum"));
		List<DailyReport> list = reportUtils.findDailyReport(page, 10);
		
//		List<DailyReport> tpage = new ArrayList<DailyReport>();
//		int count = 10;
//		int start = (page - 1) * count;
//		int end = start + count;
//		int i = 0;
//		int size = list.size();
//		while (i < size) {
//			if (i >= start && i < end) {
//				tpage.add(list.get(i));
//			}
//			i++;
//		}
		StringBuilder sbd = new StringBuilder();
		if (list != null && !list.isEmpty()) {
			sbd.append("{\"count\":" + list.size() + ",\"reports\":");
			sbd.append("[");
			for (DailyReport report : list) {
				sbd.append(report.toJson() + ",");
			}
			sbd.deleteCharAt(sbd.length() - 1);
			sbd.append("]");
			sbd.append("}");
		}

		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(sbd.toString());
	}

	/**
	 * 删除历史信息中的每日舆情（后端方法）
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void deleteReport(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String checkarray = request.getParameter("checkarray");
		if (checkarray != null && checkarray != "") {
			String[] ids = checkarray.split("_");

			for (int i = 0; i < ids.length; i++) {
				reportUtils.removeDailyReport(new ObjectId(ids[i]));
				// 删除 CrawlInfo 表中数据(微博意见)
				// List<String> infoid = report.getWeiboOpinion_id();
				// for(int j = 0; j < infoid.size(); j++){
				// CrawlInfo info = new CrawlInfo();
				// info.set_id(infoid.get(j));
				// dbu.remove(info.toDocument_id(), new String[] {"_id"});
				// }
				// 删除 DailyReport 表中数据
			}
		}
	}
	/**
	 * 获取今日已经发布的每日舆情报告，给热点舆情报告做数据源
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	public void getTodayPublishedReports(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		List<DailyReport> reports = null;
		reports = reportUtils.findDailyReport(new Date(),true);

		StringBuilder sbd = new StringBuilder();
		if (reports != null && !reports.isEmpty()) {
			sbd.append("{\"reports\":");
			sbd.append("[");
			for (DailyReport report : reports) {
				sbd.append(report.toJson() + ",");
			}
			sbd.deleteCharAt(sbd.length() - 1);
			sbd.append("]");
			sbd.append("}");
		}

		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(sbd.toString());

	}
}
